<template>
  <a-modal
    :title="`三方${model && model.id > 0 ? '编辑' : '新增'}`"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => {$emit('ok')}"
    @cancel="() => {$emit('cancel')}"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" :labelCol="{ sm: { span: 4 } }" :wrapperCol="{ sm: { span: 20 } }">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="model && model.id > 0" label="ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="名称">
          <a-input v-decorator="['name', { rules: [{ required: true, message: '名称不能为空' }] }]" placeholder="请输入三方名称"/>
        </a-form-item>
        <a-form-item label="类型">
          <a-select 
            v-decorator="['type']" 
            placeholder="请选择三方类型"
          >
            <a-select-option v-for="it in typeList" :key="it.id" :value="Number(it.id)">{{ it.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="联系人">
          <a-input v-decorator="['contactName']" placeholder="请输入联系人"/>
        </a-form-item>
        <!-- , { rules: [{ required: true, message: '名称不能为空' }] } 
          , { rules: [{ required: true, message: '名称不能为空' }] }
          , { rules: [{ required: true, message: '级别类型不能为空' }] }
        -->
        <a-form-item label="联系人号码">
          <a-input v-decorator="['contactPhone']" placeholder="请输入联系人号码"/>
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea :auto-size="{ minRows: 3, maxRows: 5 }" v-decorator="['remark']" placeholder="请输入描述"/>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
// 表单字段
const fields = ['name', 'type', 'id', 'contactName', 'contactPhone', 'remark'];


export default {
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    loading: {
      type: Boolean,
      default: () => false,
    },
    typeList: {
      type: Array,
      default: () => [],
    },
    model: {
      type: Object,
      default: () => null,
    },
  },
  data() {
    return {
      form: this.$form.createForm(this),
    }
  },
  created() {
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      let data = pick(this.model, fields)
      setTimeout(()=>{
        this.model && this.form.setFieldsValue(data)
      },0)
    })
  },
  methods: {
  },
}
</script>
